//-------------------------------------------------------------------
//	Copyright (c) 2013-2014  Zhirnov Andrey
//	This file is part of the "UX OpwnGL Framework" project.
//	See copyright notice in "UX_GL_Framework.h".
//-------------------------------------------------------------------

#pragma once

#include "VoxelsBlock.h"

namespace Voxels
{

	//
	// Voxel File Memory Cache
	//

	class VoxelFileMemCache
	{
	// types
	private:
		typedef map< uint, VoxelsBlockPtr >		block_cache_map_t;


	// variables
	private:
		block_cache_map_t	_blocksCache;
		bool				_changed;


	// methods
	public:
		VoxelFileMemCache () : _changed(true) {}

		bool Load (uint index, OUT VoxelsBlockPtr &block);
		bool Store (uint index, const VoxelsBlock &block);

		void Clear ();
		void Flush ();

		bool IsChanged ()	const	{ return _changed; }

		Bytes UsedMemory () const;
	};
	

/*
=================================================
	Load
=================================================
*/
	inline bool VoxelFileMemCache::Load (uint index, OUT VoxelsBlockPtr &block)
	{
		usize	idx = 0;

		if ( not _blocksCache.FindFirstIndex( index, idx ) )
			return false;

		block = _blocksCache[idx].second;
		return true;
	}

/*
=================================================
	Store
=================================================
*/
	inline bool VoxelFileMemCache::Store (uint index, const VoxelsBlock &block)
	{
		usize	idx = 0;

		_changed = true;

		if ( _blocksCache.FindFirstIndex( index, idx ) )
		{
			return _blocksCache[idx].second->Copy( block );
		}

		_blocksCache.Add( index, new VoxelsBlock( block ) );
		return true;
	}
	
/*
=================================================
	Clear
=================================================
*/
	inline void VoxelFileMemCache::Clear ()
	{
		_blocksCache.ClearMem();
	}

/*
=================================================
	UsedMemory
=================================================
*/
	inline Bytes VoxelFileMemCache::UsedMemory () const
	{
		Bytes size;

		FOR( i, _blocksCache )
		{
			size += Bytes( _blocksCache[i].second->Data().Size() );
		}
		return size;
	}
	
/*
=================================================
	Flush
=================================================
*/
	inline void VoxelFileMemCache::Flush ()
	{
		_changed = false;
	}


}	// Voxels
